import React, { useState, useEffect } from 'react';
import Navbar from "../Navbar.jsx";
import Sidebar from "../Sidebar.jsx";
import { BiChevronRight } from "react-icons/bi";
import { FaTachometerAlt, FaEdit, FaTrash } from "react-icons/fa";
import axios from 'axios';
import { jsPDF } from "jspdf";
import autoTable from 'jspdf-autotable';
import * as XLSX from 'xlsx';
import { useNavigate } from 'react-router-dom';

const DiscountCouponsList = () => {
  const navigate = useNavigate();
  const [entriesPerPage, setEntriesPerPage] = useState(10);
  const [currentPage, setCurrentPage] = useState(1);
  const [searchTerm, setSearchTerm] = useState('');
  const [coupons, setCoupons] = useState([]);
  const [isSidebarOpen, setSidebarOpen] = useState(true);
  const [loading, setLoading] = useState(false);
  const [dropdownIndex, setDropdownIndex] = useState(null);

  const fetchDiscountCoupons = async () => {
    try {
      setLoading(true);
      const response = await axios.get('https://mybackend-l7om.onrender.com/api/discount-coupons', {
        headers: {
          Authorization: `Bearer ${localStorage.getItem("token")}`,
        },
      });
      setCoupons(response.data);
    } catch (err) {
      alert(`Failed to fetch coupons: ${err.response?.data?.error || err.message}`);
      console.log("Fetch error:", err.response?.data || err.message);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchDiscountCoupons();
  }, []);

  useEffect(() => {
    if (window.innerWidth < 768) {
      setSidebarOpen(false);
    }
  }, []);

  const filteredData = coupons.filter(item => {
    const searchTermLower = searchTerm.toLowerCase();
    return (
      item.occasionName.toLowerCase().includes(searchTermLower) ||
      item.couponType.toLowerCase().includes(searchTermLower)
    );
  });

  const totalPages = Math.ceil(filteredData.length / entriesPerPage);
  const currentCoupons = filteredData.slice((currentPage - 1) * entriesPerPage, currentPage * entriesPerPage);

  const handlePageChange = (newPage) => {
    if (newPage >= 1 && newPage <= totalPages) {
      setCurrentPage(newPage);
    }
  };

  const handleEntriesChange = (e) => {
    setEntriesPerPage(Number(e.target.value));
    setCurrentPage(1);
  };

  const handleCopy = () => {
    const data = coupons.map(coupon => `${coupon.occasionName}, ${new Date(coupon.expiryDate).toDateString()}, ${coupon.value}, ${coupon.couponType}, ${coupon.status}`).join('\n');
    navigator.clipboard.writeText(data);
    alert("Data copied to clipboard!");
  };

  const handleExcelDownload = () => {
    const ws = XLSX.utils.json_to_sheet(coupons);
    const wb = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(wb, ws, "DiscountCoupons");
    XLSX.writeFile(wb, "discount_coupons.xlsx");
  };

  const handlePdfDownload = () => {
    const doc = new jsPDF();
    doc.text("Discount Coupons List", 20, 20);
    const tableData = coupons.map(coupon => [
      coupon.occasionName,
      new Date(coupon.expiryDate).toDateString(),
      coupon.value,
      coupon.couponType,
      coupon.status,
    ]);
    autoTable(doc, {
      head: [["Occasion Name", "Expire Date", "Value", "Coupon Type", "Status"]],
      body: tableData,
    });
    doc.save('discountCoupons.pdf');
  };

  const handlePrint = () => {
    window.print();
  };

  const handleCsvDownload = () => {
    const csvContent = "data:text/csv;charset=utf-8," + coupons.map(coupon => Object.values(coupon).join(",")).join("\n");
    const encodedUri = encodeURI(csvContent);
    const link = document.createElement("a");
    link.setAttribute("href", encodedUri);
    link.setAttribute("download", "discount_coupons.csv");
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  };

  const toggleDropdown = (index) => {
    setDropdownIndex(dropdownIndex === index ? null : index);
  };

  const handleDelete = async (id) => {
    const conf = window.confirm("Do you want to delete this?");
    if (!conf) return;
    setLoading(true);
    try {
      await axios.delete(`https://mybackend-l7om.onrender.com/api/discount-coupons/${id}`, {
        headers: {
          Authorization: `Bearer ${localStorage.getItem("token")}`,
        },
      });
      alert("Deleted Successfully");
      fetchDiscountCoupons();
    } catch (error) {
      alert(`Failed to delete coupon: ${error.response?.data?.error || error.message}`);
      console.log("Delete error:", error.response?.data || error.message);
    } finally {
      setLoading(false);
    }
  };

  const updateData = async (id, newStatus) => {
    setLoading(true);
    try {
      await axios.put(
        `https://mybackend-l7om.onrender.com/api/discount-coupons/${id}`,
        { status: newStatus },
        {
          headers: {
            "Content-Type": "application/json",
            Authorization: `Bearer ${localStorage.getItem("token")}`,
          },
        }
      );
      alert("Update Successfully");
      fetchDiscountCoupons();
    } catch (err) {
      alert(`Failed to update status: ${err.response?.data?.error || err.message}`);
      console.log("Update error:", err.response?.data || err.message);
    } finally {
      setLoading(false);
    }
  };

  const handleStatus = (id) => {
    const selectedCoupon = coupons.find((item) => item._id === id);
    if (!selectedCoupon) return;
    const newStatus = selectedCoupon.status === "Active" ? "Inactive" : "Active";
    updateData(id, newStatus);
  };

  if (loading) return <div>Loading...</div>;

  return (
    <div className="flex flex-col h-screen">
      <Navbar isSidebarOpen={isSidebarOpen} setSidebarOpen={setSidebarOpen} />
      <div className="flex flex-grow">
        <Sidebar isSidebarOpen={isSidebarOpen} />
        <div className={`flex-grow mt-24 flex flex-col p-2 md:p-2 min-h-screen ${isSidebarOpen ? "ml-64" : "ml-0"}`}>
          <header className='flex items-center justify-between'>
            <div className="flex flex-col items-center gap-1 text-center sm:flex-row sm:text-left">
              <h1 className="text-lg font-semibold truncate sm:text-xl">Discount Coupons</h1>
              <span className="text-xs text-gray-600 sm:text-sm">View/Search Items Brand</span>
            </div>
            <nav className="flex flex-wrap items-center justify-center mt-2 text-xs text-gray-500 sm:justify-start sm:text-sm sm:mt-0">
              <a href="#" className="flex items-center text-gray-800 no-underline hover:text-cyan-500">
                <FaTachometerAlt className="mr-2 text-gray-500 hover:text-cyan-500" /> Home
              </a>
              <BiChevronRight className="hidden mx-1 sm:mx-2 sm:inline" />
              <a href="#" className="text-gray-800 no-underline hover:text-cyan-500">Discount Coupons</a>
            </nav>
          </header>
          <div>
            <div className="w-full p-6 bg-white border-t-4 rounded-lg shadow-md border-cyan-500">
              <div className="flex items-center justify-between mb-4">
                <h3 className="text-xl font-semibold">Discount Coupons</h3>
                <button className="flex items-center w-full gap-2 px-4 py-2 mt-2 text-white rounded bg-cyan-300 hover:bg-cyan-500 md:w-auto md:mt-0" onClick={() => navigate("/create-coupon")}>
                  <FaTachometerAlt /> Create Coupon
                </button>
              </div>
              <div className="flex flex-col gap-4 p-4 rounded-md md:flex-row md:justify-between bg-gray-50">
                <div className="flex items-center gap-2">
                  <label className="text-sm">Show</label>
                  <select
                    className="p-2 text-sm border border-gray-300 rounded-md focus:ring-2 focus:ring-blue-400"
                    value={entriesPerPage}
                    onChange={handleEntriesChange}
                  >
                    <option value={10}>10</option>
                    <option value={25}>25</option>
                    <option value={50}>50</option>
                    <option value={100}>100</option>
                  </select>
                  <label className="text-sm">Entries</label>
                </div>
                <div className="flex flex-wrap items-center gap-0.5">
                  <button className="p-2 text-sm text-white border border-gray-300 bg-cyan-300 hover:bg-cyan-500" onClick={handleCopy}>Copy</button>
                  <button className="p-2 text-sm text-white border border-gray-300 bg-cyan-300 hover:bg-cyan-500" onClick={handleExcelDownload}>Excel</button>
                  <button className="p-2 text-sm text-white border border-gray-300 bg-cyan-300 hover:bg-cyan-500" onClick={handlePdfDownload}>PDF</button>
                  <button className="p-2 text-sm text-white border border-gray-300 bg-cyan-300 hover:bg-cyan-500" onClick={handlePrint}>Print</button>
                  <button className="p-2 text-sm text-white border border-gray-300 bg-cyan-300 hover:bg-cyan-500" onClick={handleCsvDownload}>CSV</button>
                  <input
                    type="text"
                    placeholder="Search..."
                    value={searchTerm}
                    onChange={(e) => setSearchTerm(e.target.value)}
                    className="w-full p-2 border border-gray-300 rounded-md md:w-auto focus:ring-2 focus:ring-blue-400"
                  />
                </div>
              </div>
              <div className="mt-4 overflow-x-auto">
                <table className="w-full bg-white border border-gray-300 rounded-md shadow-md">
                  <thead className="bg-gray-200">
                    <tr>
                      {["Occasion Name", "Expire Date", "Value", "Coupon Type", "Status", "Action"].map((heading) => (
                        <th key={heading} className="p-3 text-sm font-medium text-left border">{heading}</th>
                      ))}
                    </tr>
                  </thead>
                  <tbody>
                    {currentCoupons.length === 0 ? (
                      <tr>
                        <td colSpan="6" className="p-4 text-center text-gray-500">No data available in table</td>
                      </tr>
                    ) : (
                      currentCoupons.map((coupon) => (
                        <tr key={coupon._id} className="transition border hover:bg-gray-100">
                          <td className="p-3 border">{coupon.occasionName}</td>
                          <td className="p-3 border">{new Date(coupon.expiryDate).toDateString()}</td>
                          <td className="p-3 border">{coupon.value}</td>
                          <td className="p-3 border">{coupon.couponType}</td>
                          <td className="p-3 border" onClick={() => handleStatus(coupon._id)}>
                            {coupon.status.toLowerCase() === "active" ? (
                              <span className="p-1 text-white bg-green-400 rounded-md">Active</span>
                            ) : (
                              <span className="p-1 text-white bg-red-500 rounded-md">Inactive</span>
                            )}
                          </td>
                          <td className="p-3 border relative">
                            <button
                              onClick={() => toggleDropdown(coupon._id)}
                              className="px-4 py-1 text-white bg-blue-500 rounded-md hover:bg-blue-600"
                            >
                              Action ▼
                            </button>
                            {dropdownIndex === coupon._id && (
                              <div className="absolute z-10 w-32 bg-white border border-gray-200 rounded-md shadow-md right-12">
                                <button
                                  className="flex items-center w-full px-3 py-2 text-gray-700 hover:bg-gray-100"
                                  onClick={() => navigate(`/create-coupon?couponid=${coupon._id}`)}
                                >
                                  <FaEdit className="mr-2" /> Edit
                                </button>
                                <button
                                  className="flex items-center w-full px-3 py-2 text-red-600 hover:bg-gray-100"
                                  onClick={() => handleDelete(coupon._id)}
                                >
                                  <FaTrash className="mr-2" /> Delete
                                </button>
                              </div>
                            )}
                          </td>
                        </tr>
                      ))
                    )}
                  </tbody>
                </table>
              </div>
              <div className="flex flex-col items-center justify-between mt-4 md:flex-row">
                <div className="text-sm text-gray-600">
                  Showing {(currentPage - 1) * entriesPerPage + 1} to {Math.min(currentPage * entriesPerPage, filteredData.length)} of {filteredData.length} entries
                </div>
                <div className="flex gap-2">
                  <button
                    className="p-2 text-sm border rounded-md hover:bg-gray-100 disabled:opacity-50"
                    onClick={() => handlePageChange(currentPage - 1)}
                    disabled={currentPage === 1}
                  >
                    Previous
                  </button>
                  <button
                    className="p-2 text-sm border rounded-md hover:bg-gray-100 disabled:opacity-50"
                    onClick={() => handlePageChange(currentPage + 1)}
                    disabled={currentPage === totalPages}
                  >
                    Next
                  </button>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

export default DiscountCouponsList;